package com.core;

import org.opencv.core.*;
import org.opencv.highgui.HighGui;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class ColorBasedHighlighting {

    public static void main(String[] args) {

        System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
        // 加载图像
        Mat image = Imgcodecs.imread("Z:\\Users\\adwszzy\\Desktop\\789.png");

        // 转换到HSV色彩空间
        Mat hsv = new Mat();
        Imgproc.cvtColor(image, hsv, Imgproc.COLOR_BGR2HSV);

        // 设定颜色阈值
        // 设定颜色阈值
        Scalar upperBound = new Scalar(48, 255, 255); // 黄色
        Scalar lowerBound = new Scalar(46, 32, 60);

        // 创建掩码
        Mat mask = new Mat();
        Core.inRange(hsv, lowerBound, upperBound, mask);

        // 形态学操作
        Mat kernel = Imgproc.getStructuringElement(Imgproc.MORPH_ELLIPSE, new Size(5, 5));
        Imgproc.morphologyEx(mask, mask, Imgproc.MORPH_OPEN, kernel);


        // 将符合条件的像素标红
        Mat highlightedImage = image.clone();

        // 创建单独的通道
        Mat redChannel = new Mat();
        Mat greenChannel = new Mat();
        Mat blueChannel = new Mat();

        // 分离通道
        Mat[] srcChannels = {highlightedImage};
        Mat[] dstChannels = {redChannel, greenChannel, blueChannel};
        int[] fromTo = {2, 0, 1, 1, 0, 2}; // 顺序是：红色通道 -> 0, 绿色通道 -> 1, 蓝色通道 -> 2
        Core.mixChannels(Arrays.asList(srcChannels), Arrays.asList(dstChannels), new MatOfInt(fromTo));

        // 将符合条件的像素设置为红色
        Core.bitwise_and(redChannel, mask, redChannel);
        Core.multiply(greenChannel,mask,greenChannel);
        Core.multiply(blueChannel,mask,blueChannel);

        // 合并通道
        Mat[] mergedChannels = {redChannel, greenChannel, blueChannel};

        // 显示结果
//        Imgcodecs.imwrite("highlighted_image.jpg", highlightedImage);
        HighGui.imshow("模板匹配", highlightedImage);
        HighGui.waitKey();
    }
}